<template>
  <div>
    <div class="inline-form">
      <Form ref="form3" :model="form3" :rules="rules3" :label-width="120" style="display: block;">
        <FormItem prop="remedyType" label="补卡类型:">
          <Select v-model="form3.remedyType" @on-change="remedyTypeChange" clearable>
            <Option
              v-for="item in remedyTypeList"
              :key="item.key"
              :value="item.key"
              :editable="false"
            >{{item.value}}</Option>
          </Select>
          <div class="form-tip">
            <Icon type="ios-alert-outline" size="24" />
            本月已补卡{{remedyTotal.detail}}次
          </div>
        </FormItem>
        <Row v-if="onWork">
          <i-col span="18">
            <FormItem prop="remedyToDate" label="上班补卡时间:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form3.remedyToDate"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
                disabled
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="remedyToTime" :label-width="0">
              <TimePicker
                format="HH:mm"
                placeholder="请选择时间"
                v-model="form3.remedyToTime"
                :editable="false"
              ></TimePicker>
            </FormItem>
          </i-col>
        </Row>
        <Row v-if="outWork">
          <i-col span="18">
            <FormItem prop="remedyFromDate" label="下班补卡时间:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form3.remedyFromDate"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
                disabled
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="remedyFromTime" :label-width="0">
              <TimePicker
                format="HH:mm"
                placeholder="请选择时间"
                v-model="form3.remedyFromTime"
                :editable="false"
              ></TimePicker>
            </FormItem>
          </i-col>
        </Row>
        <FormItem prop="remedyReason" label="补卡事由:">
          <i-input type="textarea" v-model="form3.remedyReason" :rows="4" placeholder="请输入"></i-input>
        </FormItem>
        <FormItem prop="remedyFile" label="说明附件:">
          <Uploadv
            multiple
            ref="upload"
            type="drag"
            :before-upload="handleUpload"
            :show-upload-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadFail"
            :headers="{
              Authorization:'',
            }"
            name="multipartFile"
            :data="{
        applyNo:''
        }"
            :action="action"
          >
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>点击或将文件拖拽到这里上传</p>
            <p style="color:rgba(0,0,0,0.43)">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</p>
          </Uploadv>
          <div v-for="(item, index) in file" :key="index">
            <div>
              <Icon type="md-attach" style="transform:rotate(90deg);" />
              &nbsp;{{ item.name }}
              <span @click="delectFile(item.keyID)" class="deleteFile">X</span>
            </div>
          </div>
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            style="width:74px"
            @click="handleSubmit('form3')"
            :loading="submitLoading"
          >提交</Button>
          <Button
            type="default"
            style="width:74px;margin-left:25px"
            @click="previousStep"
            v-if="previousStepShow"
          >上一步</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    applyInfo: {
      type: String
    }
  },
  data() {
    const validateToDate = (rule, value, callback) => {
      if (this.onWork == true && value == "") {
        callback(new Error("补卡时间不能为空"));
      } else {
        callback();
      }
    };
    const validateToTime = (rule, value, callback) => {
      if (this.onWork == true && value == "") {
        callback(new Error("时间不能为空"));
      } else {
        callback();
      }
    };
    const validateFromDate = (rule, value, callback) => {
      if (this.outWork == true && value == "") {
        callback(new Error("补卡时间不能为空"));
      } else {
        callback();
      }
    };
    const validateFromTime = (rule, value, callback) => {
      if (this.outWork == true && value == "") {
        callback(new Error("时间不能为空"));
      } else {
        callback();
      }
    };
    return {
      remedyTypeList: [],
      form3: {
        remedyType: "",
        remedyToDate: "",
        remedyToTime: "",
        remedyFromDate: "",
        remedyFromTime: "",
        remedyReason: ""
      },
      rules3: {
        remedyType: [{ required: true, message: "请假类型不能为空" }],
        remedyToDate: [{ validator: validateToDate, trigger: "blur" }],
        remedyToDate: [{ validator: validateToDate, trigger: "change" }],
        remedyToTime: [{ validator: validateToTime, trigger: "blur" }],
        remedyToTime: [{ validator: validateToTime, trigger: "change" }],
        remedyFromDate: [{ validator: validateFromDate, trigger: "blur" }],
        remedyFromDate: [{ validator: validateFromDate, trigger: "change" }],
        remedyFromTime: [{ validator: validateFromTime, trigger: "blur" }],
        remedyFromTime: [{ validator: validateFromTime, trigger: "change" }]
      },
      onWork: false, // 上班打卡
      outWork: false, // 下班打卡
      file: [],
      deleteFiles: [],
      applyNo: "",
      previousStepShow: true,
      remedyTotal: "",
      fileIndex: 0,
      submitLoading: false,
      action: ""
    };
  },
  methods: {
    // 获取补卡次数和补卡请假类型
    selectRemedyCount() {
      // this.action = sessionStorage.getItem("userIp") + "api/fileupload/up";
      this.action = "/scrm-gateway/scrm-uer/api/fileupload/up";
      let obj = {
        employeeNo: "1"
      };
      // 获取补卡次数
      this.api.getApplyClockTotal(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.remedyTotal = res.data;
        }
      });
      // 获取补卡请假类型
      this.api.getNoClockIn(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          res.data.forEach(element => {
            this.remedyTypeList.push({
              key: element.key + " " + element.detail.substr(0, 10),
              value: element.detail
            });
          });
        }
      });
    },

    // 补卡类型切换
    remedyTypeChange(e) {
      let time = this.form3.remedyType.substr(3, 10);
      let type = this.form3.remedyType.substr(0, 2);
      this.form3.remedyToTime = "";
      this.form3.remedyFromTime = "";
      if (type == 17) {
        this.onWork = true;
        this.outWork = false;
        this.form3.remedyToDate = time;
      }
      if (type == 19) {
        this.onWork = true;
        this.outWork = true;
        this.form3.remedyToDate = time;
        this.form3.remedyFromDate = time;
      }
      if (type == 18) {
        this.onWork = false;
        this.outWork = true;
        this.form3.remedyFromDate = time;
      }
    },

    // 重置表单
    handleReset(name) {
      this.$refs[name].resetFields();
    },

    //提交
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          let datee = new Date(this.form3.remedyToDate).toJSON();
          let date = new Date(+new Date(datee) + 8 * 3600 * 1000).toISOString();
          let datee1 = new Date(this.form3.remedyFromDate).toJSON();
          let date1 = new Date(
            +new Date(datee1) + 8 * 3600 * 1000
          ).toISOString();
          let remedyTypeDetail = this.form3.remedyType.substr(0, 2);
          let remedyTypeDate = this.form3.remedyType.substr(3, 10);
          let obj = {
            detail: remedyTypeDate + "~" + remedyTypeDetail,
            clockInDate: date,
            clockInTime: this.form3.remedyToTime,
            clockOutDate: date1,
            clockOutTime: this.form3.remedyFromTime,
            reason: this.form3.remedyReason,
            applyNo: this.applyNo,
            uid: "1"
          };
          // 删除文件
          if (this.deleteFiles.length > 0) {
            this.deleteFiles.forEach(element => {
              if (element.id) {
                let obj = {
                  id: element.id
                };
                this.api.deleteAttachment(obj).then(res => {
                  if (res.code == 200) {
                  } else {
                    this.$Message.error(res.msg);
                    return false;
                  }
                });
              }
            });
          }
          // 提交
          this.api.addUerApplyClockIn(obj).then(res => {
            if (res.code == 200 && res.data != null) {
              if (res.data.applyNo) {
                this.$refs.upload.data.applyNo = res.data.applyNo;
                this.applyNo = res.data.applyNo;
              } else {
                this.$Message.error("文件上传失败");
              }
              this.upload();
            } else {
              this.submitLoading = false;
              this.$Message.error(res.msg);
            }
          });
        } else {
          this.$Message.error("信息填写有误");
        }
      });
    },

    // 回退到上一步
    previousStep() {
      this.$emit("currentChanged", "0");
    },

    // 保存需要上传的文件
    handleUpload(file) {
      // 保存需要上传的文件
      let keyID = Math.random()
        .toString()
        .substr(2);
      file["keyID"] = keyID;
      this.file.push(file);
      return false;
    },

    // 删除文件
    delectFile(keyID) {
      this.file = this.file.filter(item => {
        if (item.keyID == keyID) {
          // 保存到删除文件数组
          if (item.id) {
            this.deleteFiles.push(item);
          }
        }
        return item.keyID != keyID;
      });
    },

    // 上传文件
    upload() {
      this.$refs.upload.headers.Authorization = sessionStorage.getItem(
        "credentials"
      );
      if (this.file.length > 0) {
        for (let i = 0; i < this.file.length; i++) {
          let item = this.file[i];
          if (item.id) {
            // 重新提交原文件不上传
            this.fileIndex++;
            // 如果全部是原文件
            if (this.fileIndex == this.file.length) {
              this.submitLoading = false;
              this.file = [];
              this.$Message.success("补卡申请提交成功");
              // 向父组件传递事件
              this.$emit("currentChanged", "2");
              // 向父组件传递applyNo查询审批流程
              this.$emit("currentChanged", this.applyNo);
            }
          } else {
            this.$refs.upload.post(item);
          }
        }
      } else {
        this.submitLoading = false;
        this.$Message.success("补卡申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
    },

    // 文件上传成功
    uploadSuccess(response, file, fileList) {
      this.fileIndex++;
      this.$Message.success(response.data[0].name + "上传成功");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("补卡申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return true;
    },

    // 文件上传失败
    uploadFail(response, file, fileList) {
      this.fileIndex++;
      this.$Message.error(response.data[0].name + "上传失败");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("补卡申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return false;
    },

    // 填充表单
    formFill() {
      if (this.applyInfo != null) {
        this.previousStepShow = false;
        this.applyNo = this.applyInfo.applyNo;
        let obj = {
          applyNo: this.applyInfo.applyNo
        };
        this.api.getApplyInfo(obj).then(res => {
          if (res.code == 200 && res.data != null) {
            let time = res.data.clockTime.substr(7, 10);
            const remedy = new Map([
              [
                time + " " + "上班打卡异常",
                { detail: "上班未打卡", key: "17", date: time }
              ],
              [
                time + " " + "下班打卡异常",
                { detail: "下班未打卡", key: "18", date: time }
              ],
              [
                time + " " + "上下班打卡异常",
                { detail: "上下班未打卡", key: "19", date: time }
              ]
            ]);
            let remedyType = remedy.get(res.data.detail);
            if (remedyType) {
              this.form3.remedyType = remedyType.key + " " + remedyType.date;
              this.remedyTypeChange(this.form3.remedyType);
              if (remedyType.key == "17") {
                this.form3.remedyToTime = res.data.clockTime.substr(18, 5);
              }
              if (remedyType.key == "18") {
                this.form3.remedyFromTime = res.data.clockTime.substr(18, 5);
              }
              if (remedyType.key == "19") {
                this.form3.remedyToTime = res.data.clockTime.substr(18, 5);
                this.form3.remedyFromTime = res.data.clockTime.substr(43, 5);
              }
            }
            // 理由和文件不是必填
            if (res.data.reason) {
              this.form3.remedyReason = res.data.reason;
            }
            if (res.data.uerAttachment.length > 0) {
              res.data.uerAttachment.forEach(element => {
                let file = {
                  id: element.id,
                  name: element.fileName
                };
                this.handleUpload(file);
              });
            }
            // //20201215
            // this.api.getApplyInfo({
            //   agentcode:'', //还没加，待联调
            //   messageid:obj.applyNo,
            //   messagetype:4
            // }).then(res => {
            //   console.log(res)
            // })
          } else {
            this.$Message.error(res.msg);
          }
        });
      }
    }
  },
  mounted() {
    this.selectRemedyCount();
    // 填充表单
    this.formFill();
  },
  beforeDestroy() {
    // validateToDate = null;
    // validateToTime = null;
    // validateFromDate = null;
    // validateFromTime = null;
    this.remedyTypeList = null;
    this.form3 = null;
    this.rules3 = null;
    this.onWork = null; // 上班打卡
    this.outWork = null; // 下班打卡
    this.file = null;
    this.deleteFiles = null;
    this.applyNo = null;
    this.previousStepShow = null;
    this.remedyTotal = null;
    this.fileIndex = null;
    this.submitLoading = null;
    this.action = null;
  }
};
</script>

<style lang="less" scoped>
@import "./index";
</style>

<style>
textarea.ivu-input {
  resize: none;
}
</style>